import { Injectable, Inject } from "@angular/core";
import {
  Router,
  CanActivate,
  ActivatedRouteSnapshot,
  RouterStateSnapshot
} from "@angular/router";

import {
  catchError,
  exhaustMap,
  map,
  tap,
  filter,
  take,
  skip,
  last
} from "rxjs/operators";
import { Store, select } from "@ngrx/store";
import * as fromUser from "@/user/store/reducers/index";
import * as fromRoot from "@/reducers/index";
import { Subscription, Subject, Observable, of, combineLatest } from "rxjs";
import { UserActions } from "@/user/store/actions";
import { combineAll, debounceTime, skipWhile } from "rxjs/operators";
import {
  NavigationEnd,
  ActivatedRoute,
  GuardsCheckStart
} from "@angular/router";

@Injectable({
  providedIn: "root"
})
export class AuthGuardService implements CanActivate {
  // isLogin$ = this.store.pipe(
  //   select(fromRoot.userRes),
  //   filter(e => e.code !== -1),
  //   map(e => e.code === 200)
  // );

  // isLogin = false;

  constructor(
    public router: Router,
    @Inject("UserService") private userService,
    private store: Store<fromUser.State | fromRoot.State>
  ) {
    // this.isLogin$.subscribe(e => {
    //   this.isLogin = e;
    // });
  }

  // canActivate(
  //   route: ActivatedRouteSnapshot,
  //   state: RouterStateSnapshot
  // ): boolean {
  //   return this.isLogin;
  // }

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> {
    return this.userService.hasAuth().pipe(
      map((e: any) => {
        return e.data;
      }),
      tap((e: any) => {
        if (!e) {
          this.router.navigate(["u/login"]);
        }
      })
    );
  }

  // canActivate(
  //   route: ActivatedRouteSnapshot,
  //   state: RouterStateSnapshot
  // ): Observable<boolean> {
  //   return this.isLogin$.pipe(
  //     // take(1),
  //     tap(e => {
  //       console.log(e, 999999);
  //       if (!e) {
  //         // 需要权限的页面进行拦截
  //         // this.router.navigate(["/u/login"]);
  //       }
  //     })
  //   );
  // }
}
